import { getProfile } from "@/api/modules/model/profile";
import { getSchema } from "@/api/modules/model/schema";
import { SchemaItem } from "@/components/JsonForm/interface";
import BasicInfo from "./../../../components/Sansan/Model/components/BasicInfo";
import Navigation from "./../../../components/Sansan/Model/device/Navigation";

import { Device, GatewayType } from "@/api/interface/iot";
import { getDevice, modifyDevice, saveToProduct, syncDevice, syncGetDevice } from "@/api/modules/iot/device";
import PageHeader from "@/components/Frame/PageHeader";
import SaveClearBtn from "@/components/Frame/save-clear-btn";
import DeviceParam from "./../../../components/Sansan/Model/device/DeviceParam";
import SimpleInfo from "./../../../components/Sansan/Model/device/SimpleInfo";
import FuncList from "./../../../components/Sansan/Model/device/FuncList";
import SensorList from "./../../../components/Sansan/Model/device/SensorList";
import { AuthBtns, SchemaNodeKey } from "@/utils/constants";
import mittBus from "@/utils/mittBus";
import { ElMessage } from "element-plus";
import { useRoute } from "vue-router";
import OnlineStatus from "@/components/Sansan/OnlineStatus/OnlineStatus";
import SaveToProduct from "../product/components/SaveToProduct";
import { showMsg, showTips } from "@/utils/util";
import JsonView from "@/components/Sansan/Model/develop/PrviewSchemaJson";
import { IotStore } from "@/stores/modules/iot";
import { MessageType } from "@/enums/messageEnum";
import router from "@/routers";
import { useAuthButtons } from "@/hooks/useAuthButtons";
export default defineComponent({
	setup() {
		const route = useRoute();
		const iotStore = IotStore();

		const schemaInfo = ref<SchemaItem>({});
		provide(SchemaNodeKey.schema, schemaInfo);
		const gatewaySchemaInfo = ref<SchemaItem>({});
		provide(SchemaNodeKey.gatewaySchema, gatewaySchemaInfo);
		const prifileInfo = ref<any>({});
		provide(SchemaNodeKey.profile, prifileInfo);
		const gatewayPrifileInfo = ref<any>({});
		provide(SchemaNodeKey.gatewayProfile, gatewayPrifileInfo);
		const detail = reactive<any>({ detail: { type: GatewayType.Device, location: {} } });
		provide(SchemaNodeKey.detailInfo, detail);
		const disabledMod = ref(true);
		provide(AuthBtns.disabledMod, disabledMod);
		mittBus.on("refreshDeviceDetail", () => {
			init();
		});
		const buttonsList = ref<any>([]);
		onMounted(async () => {
			await init();
			// 获取页面按钮权限
			buttonsList.value = await useAuthButtons(AuthBtns.iotDevice);
			disabledMod.value = !buttonsList.value.some((item: any) => item.path == AuthBtns.pathMod);
		});
		const init = async () => {
			await initDevice();
			await initProfile();
			await initGatewayProfile();
			await initGatewaySchema();
			await initSchema();
		};
		//初始化设备信息
		const initDevice = async () => {
			let { result, code } = await getDevice({ idSn: route.query.sn });
			if (code == 200) {
				detail.detail = result;
			} else {
				showMsg("未找到相关数据", MessageType.error);
				timeOut.value = setTimeout(() => {
					router.go(-1);
				}, 3000);
			}
		};
		//未找到设备数据时三秒后返回上级页面
		let timeOut = ref();
		//销毁定时器
		onBeforeUnmount(() => {
			clearInterval(timeOut.value);
			timeOut.value = "";
		});
		const initSchema = async () => {
			const { result, code } = await getSchema({ idSn: route.query.sn });
			if (code == 200) schemaInfo.value = result.schema;
		};
		const initProfile = async () => {
			const { result, code } = await getProfile({ idSn: route.query.sn });
			if (code == 200) prifileInfo.value = result;
		};
		const initGatewaySchema = async () => {
			if (detail.detail.gatewaySn && route.query.sn != detail.detail.gatewaySn) {
				const { result, code } = await getSchema({ idSn: detail.detail.gatewaySn });
				if (code == 200) gatewaySchemaInfo.value = result.schema;
			} else {
				//网关是当前设备
				gatewaySchemaInfo.value = schemaInfo.value;
			}
		};
		const initGatewayProfile = async () => {
			if (detail.detail.gatewaySn && route.query.sn != detail.detail.gatewaySn) {
				const { result, code } = await getProfile({
					idSn: detail.detail.gatewaySn,
					path: `config.subdevice.${route.query.sn}`
				});
				if (code == 200) gatewayPrifileInfo.value = result;
			} else {
				//网关是当前设备
				gatewayPrifileInfo.value = prifileInfo.value;
			}
		};

		const currNav = ref<string>("");
		const basicDialog = reactive({
			title: "修改设备基本信息",
			visible: false
		});
		const changeNav = (nav: string) => {
			currNav.value = nav;
		};
		const submitBasic = async () => {
			let { success } = await modifyDevice({ ...detail.detail });
			if (success) {
				ElMessage.success("修改设备成功");
				basicDialog.visible = false;
				initDevice();
			} else {
				ElMessage.error("修改设备失败！");
			}
		};

		//按钮事件
		const handleFn = function (fn: String, data?: any) {
			switch (fn) {
				case "saveToProduct":
					saveToProductDialog.formData.id = data.sn;
					saveToProductDialog.formData.name = data.name;
					saveToProductDialog.visible = true;
					break;
				case "sync":
					syncDevice({ idSn: data.sn }).then(res => {
						showTips(res.code, "下发同步配置命令");
					});
					break;
				case "syncGet":
					syncGetDevice({ idSn: data.sn }).then(res => {
						showTips(res.code, "下发参数设置命令");
						init();
					});
					break;
			}
		};
		const saveToProductDialog = reactive<any>({
			visible: false,
			formData: {
				id: "",
				name: "",
				type: GatewayType.Device
			}
		});

		const submitToProduct = async (data: Device.ReqProduct) => {
			data.idSn = data.id;
			let { code, message } = await saveToProduct(data);
			let ok = showTips(code, "设备另存为产品", message);
			if (ok) saveToProductDialog.visible = false;
		};
		return () => {
			return (
				<div class="">
					{iotStore.isMaxDetail ? null : (
						<>
							<PageHeader
								showBackText={false}
								v-slots={{
									operate: () => {
										return (
											<>
												<el-button onClick={() => handleFn("saveToProduct", detail.detail)}>另存为产品</el-button>
												{/* <el-button class="iconfont iconbx-skip-next-circle" onClick={() => handleFn("sync", detail.detail)}>
													同步配置
												</el-button>
												<el-button class="iconfont iconbx-skip-next-circle" onClick={() => handleFn("syncGet", detail.detail)}>
													参数设置
												</el-button> */}
												{!disabledMod.value && <SaveClearBtn v-model={basicDialog.visible} onSubmit={() => submitBasic()} />}
											</>
										);
									}
								}}
							>
								<span>{detail.detail.name || detail.detail.sn}</span>
								<OnlineStatus v-model={detail.detail.onlineStatus} class="ml-4 mr-4" />
								<el-link
									class="iconfont iconbx-sync ml-2"
									type="primary"
									onClick={() => {
										init();
									}}
								>
									刷新
								</el-link>
							</PageHeader>

							<SaveToProduct
								title="另存为产品"
								v-model:visible={saveToProductDialog.visible}
								formData={saveToProductDialog.formData}
								onSubmit={(data: Device.ReqProduct) => {
									submitToProduct(data);
								}}
							></SaveToProduct>
						</>
					)}
					{/* <BasicDialog
						title={basicDialog.title}
						v-model:visible={basicDialog.visible}
						detail={detail.detail}
						onSubmit={() => {
							submitBasic();
						}}
					></BasicDialog> */}

					{Object.keys(schemaInfo.value).length ? (
						<>
							{iotStore.isMaxDetail ? null : (
								<div class="mb-4 p-4 bg-white ">
									{/* 基本信息：名称、分组、网关 */}
									<SimpleInfo visible={basicDialog.visible} />
								</div>
							)}

							<div class="iot-detail-content">
								{/* 导航分类：基本信息、设备参数、设备模型、设备日志 */}
								<Navigation onChange={val => changeNav(val)} />

								<div class="bg-white detail-type-detail">
									{/*基本信息*/}
									{currNav.value == SchemaNodeKey.basic ? <BasicInfo type={GatewayType.Device} /> : null}
									{/*设备配置信息--接入地址、接入端口*/}
									{currNav.value == SchemaNodeKey.config ? <DeviceParam /> : null}
									{/*设备模型*/}
									{currNav.value == SchemaNodeKey.sensor ? <SensorList /> : null}
									{/* 控制功能 */}
									{currNav.value == SchemaNodeKey.funcs ? <FuncList /> : null}
									{/*模型定义*/}
									{currNav.value == SchemaNodeKey.extDevelop ? <JsonView type={GatewayType.Device} /> : null}
								</div>
							</div>
						</>
					) : (
						""
					)}
				</div>
			);
		};
	}
});
